package com.zrc.module_find.activity.defrecycleview.demo3

import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.zrc.superframe_base.ARouterHub
import com.zrc.superframe_base.mvx.mvvm.BaseMvvmFragment
import com.zrc.module_find.R
import com.zrc.module_find.BR
import com.zrc.module_find.databinding.FragmentDemo3Binding
import com.zrc.module_find.viewmodel.FindVM
import com.zrc.superframe_ui.stateview.state.EmptyState
import com.zrc.superframe_ui.stateview.state.ErrorState
import com.zrc.superframe_ui.stateview.state.SuccessState
import kotlinx.android.synthetic.main.item.*

/**
 * @Author: superman
 * @CreateTime: 6/27/21
 * @Describe:
 */
@Route(path = ARouterHub.FRAGMENT_DEMO3, name = "aaa")
class Demo3Fragment : BaseMvvmFragment<FragmentDemo3Binding, FindVM>() {

    override fun getVariableId() = BR.viewModel

    override fun getLayoutId()=R.layout.fragment_demo3

    override fun getViewModel()=FindVM(this)

    private var page: Int = 1
    private lateinit var adapter: DemoAdapter

    override fun initObserver() {
        super.initObserver()
        mBinding.rv.layoutManager = LinearLayoutManager(activity)
        adapter = DemoAdapter(myScrollView)
        mBinding.rv.adapter = adapter

        mBinding.smartRefreshLayout.setOnRefreshListener {
            mViewModel.getData(true, page)
        }

        mBinding.smartRefreshLayout.setOnLoadMoreListener {
            mViewModel.getData(false, page)
        }

        mViewModel.demoLiveData.observe(this, {
            if (it.isRefrensh)
                mBinding.smartRefreshLayout.finishRefresh()
            else
                mBinding.smartRefreshLayout.finishLoadMore()

            if (it.isRefrensh) {
                adapter.setData(it.data)
            } else {
                adapter.addData(it.data)
            }

            when (it.code) {
                -1 -> {
                    if (adapter.datas.isNullOrEmpty()) {
                        mBinding.container.show<ErrorState> {
                            it.setErrorIcon(R.drawable.vector_error)
                            it.setErrorMsg("出错了")
                            it.retry {
                                mBinding.smartRefreshLayout.autoRefresh()
                            }
                        }
                    }
                }
                -2 -> {
                    if (adapter.datas.isNullOrEmpty()) {
                        mBinding.container.show<EmptyState> {
                            it.setEmptyIcon(R.drawable.vector_error)
                            it.setEmptyMsg("暂无数据")
                        }
                    }
                }
                else -> {
                    mBinding.container.show<SuccessState>()
                }
            }
            page++
        })

        mViewModel.getData(true, page)
    }
}